package com.mmz.gulimall.search.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 1.导入依赖
 * 2.编写配置，给容器中注入一个RestHighLevelClient
 */
@Configuration
@RefreshScope
public class GulimallElasticsearchConfig {
    /**
     * 主机名
     */
    @Value("${el.hostName}")
    private String hostName;
    /**
     * 端口号
     */
    @Value("${el.port}")
    private Integer port;
    /**
     * 访问协议
     */
    @Value("${el.scheme}")
    private String scheme;


    /**
     * 通用配置（安全）
     */
    public static final RequestOptions COMMON_OPTIONS;
    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
//        builder.addHeader("Authorization", "Bearer " + TOKEN);
//        builder.setHttpAsyncResponseConsumerFactory(
//                new HttpAsyncResponseConsumerFactory
//                        .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));
        COMMON_OPTIONS = builder.build();
    }


    @Bean(name = "restHighLevelClient")
    public RestHighLevelClient esRestClient() {
        RestClientBuilder builder = RestClient.builder(new HttpHost(hostName, port, scheme));
        RestHighLevelClient client = new RestHighLevelClient(builder);
        return client;
    }
}
